<template>
<div>
  <el-container>
    <el-header><Title></Title></el-header>
    <el-main>
      <!--      输入框-->
      <el-row :gutter="10">
        <el-col :xs="3" :sm="3" :md="3" :lg="4" :xl="3">
          <el-upload
              ref="upload"
              action="https://jsonplaceholder.typicode.com/posts/"
              class="upload-demo"
              accept="xls,xlsx"
              :show-file-list="false"
              :auto-upload="false"
              :multiple="false"
              :on-change="fileOnChange">
            <el-button slot="trigger" size="small" type="primary"  icon="el-icon-plus">处方导入</el-button>

          </el-upload>
        </el-col>
        <el-col :xs="3" :sm="3" :md="3" :lg="4" :xl="3">
          <div   class="minNum" >获取要对关联度：</div>

        </el-col>
        <el-col :xs="3" :sm="3" :md="3" :lg="4" :xl="3">
          <el-input
              placeholder="请输入药对关联度系数阈值"
              v-model="thresholdvalue"
              clearable>
          </el-input>
        </el-col>

        <el-col :xs="3" :sm="3" :md="3" :lg="4" :xl="3">
          <el-button type="primary" @click="GetAssocation">获取药对关联度</el-button>
        </el-col>
        <el-col :xs="3" :sm="3" :md="3" :lg="3" :xl="3">
          <el-button

              style="margin-left: 20px;width: 200px"
              type="primary"
          >
            <download-excel class="export-excel-wrapper"   name ="" :data="AssocationTableData" :fields="json_fields_Assocation"  >
            </download-excel>
          </el-button>
        </el-col>
      </el-row>
      <!--      分割线-->
      <div class="fengexian"></div>
<!--      展示数据-->
      <el-row :gutter="10">
        <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8" v-if="tableFlag">
          <el-table
              :data="currentPageList"
              stripe
              style="width: 100%">
            <el-table-column
                prop="source"
                label="中药"
                width="150">
            </el-table-column>
            <el-table-column
                prop="target"
                label="被关联中药"
                width="150">
            </el-table-column>
            <el-table-column
                prop="value"
                label="关联度系数">
            </el-table-column>
          </el-table>
<!--          分页-->
          <el-pagination

              page-size="7"
              @current-change="currentOnchange"
              @prev-click="prevOnclick"
              @next-click="nextOnclick"
              @size-change="sizeOnchange"
              layout="total,prev, pager, next"
              :total="totalSize">
          </el-pagination>
         </el-col>
        <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
          <div style="height: 600px ; ">
            <div  id="echartsGraphCluster" style="width: 480px;height: 370px ;  padding-bottom: 100px"></div>
          </div>
        </el-col>
<!--        药物相关信息查询-->
        <el-col :xs="4" :sm="8" :md="8" :lg="8" :xl="8">
          <div id="contentCenterDIV">
            <div id="medicineImgUrl">
<!--              {{this.MySQLData.imgurl}}-->
              <el-image v-if="flagSQL"
                  style="width: 150px; height: 150px"
                  :src=this.MySQLData.imgurl
                  ></el-image>
            </div>
            <div id="medicineNameDIV">
              <div id="medicineNANE" v-if="flagSQL">药名：</div>
              <div id="medicineVALUE" > {{this.MySQLData.medicinename}}</div>
            </div>
            <div id="efficacyDIV">
              <div id="efficacyNAME" v-if="flagSQL">功效：</div>
              <div id="efficacyVALUE">{{this.MySQLData.efficacy}}</div>
            </div>
            <div id="propertiesDIV">
              <div id="propertiesNAME" v-if="flagSQL" >性状:</div>
              <div id="propertiesVALUE">{{this.MySQLData.properties}}</div>
            </div>
          </div>
        </el-col>

      </el-row>
    </el-main>
    <el-footer><FooterTitle></FooterTitle></el-footer>
  </el-container>

</div>
</template>

<script>
import Title from "../../components/Title";
import FooterTitle from "../../components/FooterTitle";
import XLSX from "xlsx";
export default {
  name: "ClusterAnalysiGetAssocation",
  components:{
    Title,
    FooterTitle
  },
  created() {
    //this.test();
  },
  data(){
    return{
      tableFlag:false,
      thresholdvalue:"",
      assocationExcelJson:"",
      AssocationTableData:Array,
      AssocationNetData:Array,
      json_fields_Assocation:{
        "中药": "source", //常规字段
        "被关联中药":"target",
        "关联系数":"value"
      },
      totalSize:0,
      pageVal:1,
      currentPageList:Array,
      // 数据库查询出来的结构
      MySQLData:"",
      flagSQL:false,
      //设置网络图的参数
      optionAssocation :{
        title: {
          text: '网络图'
        },
        legend:{
          align:"left",
          marginLeft:-15,
        },
        tooltip: {},
        animationDurationUpdate: 1500,
        animationEasingUpdate: 'quinticInOut',
        toolbox: {

          feature: {
            mark:{show:true},
            saveAsImage: {
              show: true,
              pixelRatio:1,
              title:"下载",
              type:'png',
              lang:['点击保存'],
              name:"关联分析网络图"
            }
          }
        },
        series: [
          {



            right:20,
            // bottom:20,
            type: 'graph',
            layout:"force",
            roam: true,
            draggable: true,
            force: {
              initLayout:"circular" ,//力引导的初始化布局，默认使用xy轴的标点
              repulsion: 10000, //节点之间的斥力因子。支持数组表达斥力范围，值越大斥力越大。
              gravity: 2, //节点受到的向中心的引力因子。该值越大节点越往中心点靠拢。
              edgeLength: 50, //边的两个节点之间的距离，这个距离也会受 repulsion。[10, 50] 。值越小则长度越长
              layoutAnimation: true
              //因为力引导布局会在多次迭代后才会稳定，这个参数决定是否显示布局的迭代动画，在浏览器端节点数据较多（>100）的时候不建议关闭，布局过程会造成浏览器假死。
            },
            // symbolSize:30,
            label: {
              show: true,
              text: 'hhh'
            },
            symbolSize: (rawValue, params) => {
              console.log(params)
              console.log(params.data)
              console.log(params.dataIndex)
              return 30
            },

            focusNodeAdjacency: true,
            edgeSymbol: ['circle', 'arrow'],
            // edgeSymbolSize: [10, 200],
            // edgeLabel: {
            //   fontSize: 12
            // },

            itemStyle: {
              //配置节点的颜色已及尺寸
              normal: {
                // （1） 直接写一个颜色，这样的结果是所有节点都是同一个颜色
                // color: '#DC143C',
                borderWidth:"auto"
              },

            },

            links:Array,

            data:Array,
            // links: [],
            lineStyle: {
              opacity: 0.9,
              width: 2,
              curveness: 0
            }
          }
        ]
      },
      EchartAssociationColum:""
    }
  },
  methods:{
    fileOnChange(file, fileList){
      let files = {0:file.raw}
      this.readExcel1(files);
    },
    readExcel1(files) {//表格导入
      var that = this;
      if(files.length<=0){//如果没有文件名
        return false;
      }else if(!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())){

        this.$message.error('上传格式不正确，请上传xls或者xlsx格式');
        return false;
      }
      const fileReader = new FileReader();
      fileReader.onload = (ev) => {
        try {
          const data = ev.target.result;
          const workbook = XLSX.read(data, {
            type: 'binary'
          });

          const wsname1 = workbook.SheetNames[0];//取第一张表
          console.log(wsname1)
          const ws1 = XLSX.utils.sheet_to_json(workbook.Sheets[wsname1]);//生成第一张表的json表格内容
          console.log(ws1.length)
          var medicineArray = new Array();
          for(var i=0;i<ws1.length;i++){
            medicineArray.push(ws1[i].处方)
          }

          //console.log(medicineArray)

          this.assocationExcelJson = medicineArray;
          try{
          }catch(err){
            console.log(err)
          }
          this.$refs.upload.value = '';
        } catch (e) {
          return false;
        }
      };
      fileReader.readAsBinaryString(files[0]);
    },
    //获取关联度的网络请求
    getAssocationAxiosServer(){
      var that = this
      this.$axios.post('http://localhost:8800/getAssocation', {
        thresholdvalue:this.thresholdvalue,
        excel:this.assocationExcelJson
      })
          .then(function(response) {
            console.log(response.data)
            that.tableFlag = true
            that.AssocationTableData =  JSON.parse(JSON.stringify(response.data.data))
            that.AssocationNetData =  JSON.parse(JSON.stringify(response.data.name))
            that.ClusterinitNetChartDiagram()
            // console.log("that.AssocationNetData  is")
            // console.log( JSON.parse(JSON.stringify(that.AssocationNetData)))
            that.totalSize = that.AssocationTableData.length
            //返回前七条数据
            let AllListSize = that.AssocationTableData.length
            // console.log("AllListSize:"+AllListSize
            if(AllListSize>7){
              that.currentPageList=JSON.parse(JSON.stringify(that.AssocationTableData.slice(0,7)));
            }else{
              that.currentPageList=JSON.parse(JSON.stringify(that.AssocationTableData.slice(0,AllListSize)));
            }
          }).catch(function(error) {
        console.log("error")
      })
    },
    //对数据进行校验
   checkData(excel_json,association_num){
     if (excel_json.length == 0) {
       this.$message({
         message: '请传入excel处方',
         center: true,
         type: 'error'
       });
     }
     //药对信息
     else if (association_num.length == 0  || (association_num>=1 || association_num<=0)) {
       this.$message({
         message: '请输入合法的阈值（阈值在0~1之间）',
         center: true,
         type: 'error'
       });
     }else{
       this.getAssocationAxiosServer();

     }
   },
    //点击按钮获取药物以及关联度
    GetAssocation(){
      this.checkData(this.assocationExcelJson,this.thresholdvalue);
    },
    //初始化网络图
    ClusterinitNetChartDiagram(){
      console.log("initNetChartDiagram")
      this.optionAssocation.series[0].links =JSON.parse(JSON.stringify(JSON.parse(JSON.stringify(this.AssocationTableData))))
      this.optionAssocation.series[0].data =JSON.parse(JSON.stringify(JSON.parse(JSON.stringify(this.AssocationNetData))))
      this.EchartAssociationColum = this.$echarts.init(document.getElementById("echartsGraphCluster"));
      this.EchartAssociationColum.setOption(this.optionAssocation)
      var that=this;
      // 查询mysql的方法，点击单个节点触发
      // 调用数据库，查询药物的功效等信息
      this.EchartAssociationColum.on('click',function (params) {
        that.$axios.post('http://localhost:8800/searchMedicine', {
          MName:params.name
        })
            .then(function(response) {
              // console.log(response.data)
              that.MySQLData= JSON.parse(JSON.stringify(response.data));
             that.flagSQL = true;
              // that.medicinename =response.data.medicinename;
              // that.efficacy =response.data.efficacy;
              // that.properties =response.data.properties;

            }).catch(function(error) {
          console.log("error")
        })

      })

    },
    // 表单分页功能
    //当页数发生改变时，触发的事件
    sizeOnchange(val){
      console.log(`pageSize 改变时会触发 ${val} 条`);
      this.pageVal = val
      //返回前七条数据
      let AllListSize = this.AssocationTableData.length
      if((AllListSize-7*(this.pageVal-1))>0){
        console.log("(AllListSize-7*(this.pageVal))>7:::"+(AllListSize-7*(this.pageVal))>7)
        this.currentPageList=JSON.parse(JSON.stringify(this.AssocationTableData.slice(7*(this.pageVal-1),7*this.pageVal)));
      }else{
        this.currentPageList=JSON.parse(JSON.stringify(this.AssocationTableData.slice((AllListSize-7*(this.pageVal-2)),(AllListSize-7*(this.pageVal-1)))));
      }
      console.log(`前一页 ${val} 条`);

    },
    currentOnchange(val){
      this.pageVal = val
      //返回前七条数据
      let AllListSize = this.AssocationTableData.length
      if((AllListSize-7*(this.pageVal-1))>0){
        console.log("(AllListSize-7*(this.pageVal))>7:::"+(AllListSize-7*(this.pageVal))>7)
        this.currentPageList=JSON.parse(JSON.stringify(this.AssocationTableData.slice(7*(this.pageVal-1),7*this.pageVal)));
      }else{
        this.currentPageList=JSON.parse(JSON.stringify(this.AssocationTableData.slice((AllListSize-7*(this.pageVal-2)),(AllListSize-7*(this.pageVal-1)))));
      }
      console.log(`当前页: ${val} `);
    },
    prevOnclick(val){
      this.pageVal = val
      //返回前七条数据
      let AllListSize = this.AssocationTableData.length
      if((AllListSize-7*(this.pageVal-1))>0){
        console.log("(AllListSize-7*(this.pageVal))>7:::"+(AllListSize-7*(this.pageVal))>7)
        this.currentPageList=JSON.parse(JSON.stringify(this.AssocationTableData.slice(7*(this.pageVal-1),7*this.pageVal)));
      }else{
        this.currentPageList=JSON.parse(JSON.stringify(this.AssocationTableData.slice((AllListSize-7*(this.pageVal-2)),(AllListSize-7*(this.pageVal-1)))));
      }
      console.log(`前一页 ${val} 条`);
    },
    nextOnclick(val){
      this.pageVal = val

      //返回前七条数据
      let AllListSize = this.AssocationTableData.length
      if((AllListSize-7*(this.pageVal-1))>0){
        console.log("(AllListSize-7*(this.pageVal))>7:::"+(AllListSize-7*(this.pageVal))>7)
        this.currentPageList=JSON.parse(JSON.stringify(this.AssocationTableData.slice(7*(this.pageVal-1),7*this.pageVal)));
      }else{
        this.currentPageList=JSON.parse(JSON.stringify(this.AssocationTableData.slice((AllListSize-7*(this.pageVal-2)),(AllListSize-7*(this.pageVal-1)))));
      }
      console.log(`下一页 ${val} 条`);
    },
   },


}
</script>

<style scoped>
.minNum{
  font-family: "Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","微软雅黑",Arial,sans-serif;
  font-size: 14px ;
  margin-left: -20px;
  line-height: 2.2;
}
.fengexian{
  position: relative;
  margin: 15px ;
  width:100%;
  height: 1px;
  background-color: #d4d4d4;
  text-align: center;
  font-size: 16px;
  color: rgba(101, 101, 101, 1);

}
#medicineImgUrl{
  margin-bottom: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}
#contentCenterDIV{
  width: 100%;
  height: 100%;
  /*background: #da0758;*/
}
#medicineNameDIV{
  width: 100%;
  height: 10%;
  /*background: #20b8f1;*/
  display: flex;
}

#medicineNANE{
  font-size: medium;
  font-family: 方正粗黑宋简体;;
  width: 150px;
}
#medicineVALUE{
  font-size: medium;
  font-family: 宋体;
}
#efficacyDIV{
  margin-top: 50px;
  width: 100%;
  height: 40%;
  /*background: #9b5572;*/
  display: flex;
}
#efficacyNAME{
  font-size: medium;
  font-family: 方正粗黑宋简体;;
  width: 100px;
  /*background: #da0758*/
}
#efficacyVALUE{
  font-size: medium;
  font-family: 宋体;
}
#propertiesDIV{
  margin-top: 50px;
  width: 100%;
  height: 50%;
  /*background: #7b77f1;*/
  display: flex;
}
#propertiesNAME{
  font-size: medium;
  font-family: 方正粗黑宋简体;;
  width: 250px;
  /*background: #da0758*/
}

#propertiesVALUE{
  font-size: medium;
  font-family: 宋体;
}

</style>
